package com.qgz.tools.statisics;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.qgz.tools.R;
import com.qgz.tools.statisics.db.DBManager;
import com.qgz.tools.statisics.entity.ProvinceAreaEntity;
import com.qgz.tools.utils.JsoupUtils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.ArrayList;
import java.util.List;


public class StaticCityAreaHtmlActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tvStaticCity;
    private TextView tvProvince;
    private String baseUrl = "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2018/";
    private List<ProvinceAreaEntity> list = new ArrayList<>();
    private int threadTime = 1000;
    private int timeoutTime = 50000;
    private StringBuffer errorUrl = new StringBuffer();
    private EditText etErrorUrl;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_static_city_area);
        tvStaticCity = findViewById(R.id.tvStaticCity);
        tvStaticCity.setOnClickListener(this);
        tvProvince = findViewById(R.id.tvProvince);
        tvProvince.setOnClickListener(this);
        etErrorUrl = findViewById(R.id.etErrorUrl);
    }


    private void fetchData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    DBManager dbManager = new DBManager();
                    Document document = JsoupUtils.getDocument(baseUrl + "index.html");
                    Elements elements = document.select("table[class=provincetable] > tbody > tr[class=provincetr] > td");
                    ProvinceAreaEntity provinceEntity;
                    for (Element element : elements) {
                        String provinceName = element.select("td > a").get(0).text();
                        String provinceCode = element.select("td > a").get(0).attr("href").replace(".html", "");
                        String provinceHref = element.select("td > a").get(0).attr("href");
                        Log.e("eee", provinceName + "，省份信息已经获取到");
                        doGatherCityData(dbManager, provinceName, provinceCode, provinceHref);
                    }
                    Log.e("eee", "完成");
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void fetchAllProvinceData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "北京市", "11", "11.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "天津市", "12", "12.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "河北省", "13", "13.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "山西省", "14", "14.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "内蒙古自治区", "15", "15.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "辽宁省", "21", "21.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "吉林省", "22", "22.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "黑龙江省", "23", "23.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "上海市", "31", "31.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "江苏省", "32", "32.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "浙江省", "33", "33.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "安徽省", "34", "34.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "福建省", "35", "35.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "江西省", "36", "36.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "山东省", "37", "37.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "河南省", "41", "41.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "湖北省", "42", "42.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "湖南省", "43", "43.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "广东省", "44", "44.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "广西壮族自治区", "45", "45.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "海南省", "46", "46.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "重庆市", "50", "50.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "四川省", "51", "51.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "贵州省", "52", "52.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "云南省", "53", "53.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "西藏自治区", "54", "54.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "陕西省", "61", "61.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "甘肃省", "62", "62.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "青海省", "63", "63.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "宁夏回族自治区", "64", "64.html");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                DBManager dbManager = new DBManager();
                doGatherCityData(dbManager, "新疆维吾尔自治区", "65", "65.html");
            }
        }).start();
    }

    private void doGatherCityData(DBManager dbManager, String provinceName, String provinceCode, String provinceHref) {
        ProvinceAreaEntity provinceEntity;// 开始循环市信息
        String cityUrl = baseUrl + provinceHref;
        try {
            provinceEntity = new ProvinceAreaEntity();
            provinceEntity.setCode(provinceCode);
            provinceEntity.setName(provinceName);
            provinceEntity.setParentId("0");
            provinceEntity.setLevel("0");
            provinceEntity.setTypeCode("");
            dbManager.addProvince(provinceEntity);
            Thread.sleep(threadTime);
            Document cityDocument = JsoupUtils.getDocument(cityUrl);
            Elements cityElements = cityDocument.select("table[class=citytable] > tbody > tr[class=citytr]");
            for (Element cityElement : cityElements) {
                String cityName = cityElement.select("td > a").get(1).text();
                String cityCode = cityElement.select("td > a").get(0).text();
                String cityTarget = cityElement.select("td > a").get(0).attr("href");
                Log.e("eee", provinceName + "--" + cityName + "，城市信息已经获取到");
                provinceEntity = new ProvinceAreaEntity();
                provinceEntity.setCode(cityCode);
                provinceEntity.setName(cityName);
                provinceEntity.setParentId(provinceCode);
                provinceEntity.setLevel("1");
                provinceEntity.setTypeCode("");
                dbManager.addProvince(provinceEntity);
                Thread.sleep(threadTime);
                //开始循环区信息
                String countyUrl = baseUrl + cityTarget;
                try {
                    Document countyDocument = JsoupUtils.getDocument(countyUrl);
                    Elements countyElements = countyDocument.select("table[class=countytable] > tbody > tr[class=countytr]");
                    for (Element countyElement : countyElements) {
                        String tdText = countyElement.select("td").get(0).html();
                        String countyName = "";
                        String countyCode = "";
                        String countyTarget = "";
                        if (tdText.contains("<a href=")) {
                            countyName = countyElement.select("td > a").get(1).text();
                            countyCode = countyElement.select("td > a").get(0).text();
                            countyTarget = countyElement.select("td > a").get(0).attr("href");
                        } else { // 没有超链接
                            countyName = countyElement.select("td").get(1).text();
                            countyCode = countyElement.select("td").get(0).text();
                            countyTarget = "";
                        }
                        Log.e("eee", provinceName + "--" + cityName + "--" + countyName + "，区信息已经获取到");
                        provinceEntity = new ProvinceAreaEntity();
                        provinceEntity.setCode(countyCode);
                        provinceEntity.setName(countyName);
                        provinceEntity.setParentId(cityCode);
                        provinceEntity.setLevel("2");
                        provinceEntity.setTypeCode("");
                        dbManager.addProvince(provinceEntity);
                        Thread.sleep(threadTime);
                        String townName = "";
                        String townCode = "";
                        //开始循环
                        if (!TextUtils.isEmpty(countyTarget)) {
                            String urlSuffix = countyCode.substring(0, 2);
                            String townUrl = baseUrl + urlSuffix + "/" + countyTarget;
                            try {
                                Document townDocument = JsoupUtils.getDocument(townUrl);
                                Elements townElements = townDocument.select("table[class=towntable] > tbody > tr[class=towntr]");
                                for (Element townElement : townElements) {
                                    townName = townElement.select("td > a").get(1).text();
                                    townCode = townElement.select("td > a").get(0).text();
                                    String townTarget = townElement.select("td > a").get(0).attr("href");
                                    Log.e("eee", provinceName + "--" + cityName + "--" + countyName + "--" + townName + "，街道办事处信息已经获取到");
                                    provinceEntity = new ProvinceAreaEntity();
                                    provinceEntity.setCode(townCode);
                                    provinceEntity.setName(townName);
                                    provinceEntity.setParentId(countyCode);
                                    provinceEntity.setLevel("3");
                                    provinceEntity.setTypeCode("");
                                    dbManager.addProvince(provinceEntity);
                                    Thread.sleep(threadTime);
                                    // 开始循环
                                    String allUrlSuffix = townCode.substring(0, 2) + "/" + townCode.substring(2, 4);
                                    String villageUrl = "";
                                    try {
                                        villageUrl = baseUrl + allUrlSuffix + "/" + townTarget;
                                        Document villageDocument = JsoupUtils.getDocument(villageUrl);
                                        Elements villageElements = villageDocument.select("table[class=villagetable] > tbody > tr[class=villagetr]");
                                        for (Element villageelement : villageElements) {
                                            String villageName = villageelement.select("td").get(2).text();
                                            String villageCode = villageelement.select("td").get(0).text();
                                            String villageType = villageelement.select("td").get(1).text();
                                            Log.e("eee", provinceName + "--" + cityName + "--" + countyName + "--" + townName + "--" + villageName + "，社区居委会信息已经获取到");
                                            provinceEntity = new ProvinceAreaEntity();
                                            provinceEntity.setCode(villageCode);
                                            provinceEntity.setName(villageName);
                                            provinceEntity.setParentId(townCode);
                                            provinceEntity.setLevel("4");
                                            provinceEntity.setTypeCode(villageType);
                                            dbManager.addProvince(provinceEntity);
                                            Thread.sleep(threadTime);
                                        }
                                    } catch (Exception e) {
                                        Log.e("eee", villageUrl + "，社区居委会信息出错" + e.getMessage());
                                        errorUrl.append(villageUrl).append("<br/>");
                                        Message message = new Message();
                                        message.what = 0;
                                        handler.sendMessage(message);
                                        e.printStackTrace();
                                    }
                                }
                            } catch (Exception e) {
                                Log.e("eee", "错误URL"+townUrl + "，街道办事处信息出错" + e.getMessage());
                                errorUrl.append(townUrl).append("<br/>");
                                Message message = new Message();
                                message.what = 0;
                                handler.sendMessage(message);
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    Log.e("eee", countyUrl + "，区信息出错" + e.getMessage());
                    errorUrl.append(countyUrl).append("<br/>");
                    Message message = new Message();
                    message.what = 0;
                    handler.sendMessage(message);
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            errorUrl.append(cityUrl).append("<br/>");
            Log.e("eee", cityUrl + "，城市信息出错" + e.getMessage());
            Message message = new Message();
            message.what = 0;
            handler.sendMessage(message);
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvStaticCity:
                Log.e("eee", "准备开始采集国空统计局数据库");
                fetchData();
                break;
            case R.id.tvProvince:
                Log.e("eee", "准备开始采集国家统计局数据库");
                fetchAllProvinceData();
                break;
        }
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    etErrorUrl.setText("");
                    etErrorUrl.setText(Html.fromHtml(errorUrl.toString()));
                    break;
            }
        }
    };
}
